import React, { Component } from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Link } from 'react-router'
import { Table, Spin, Form, Row, Col, Input, Button, Tree, Select, Modal, Dropdown, Menu, Popconfirm, Icon, message, Checkbox } from 'antd'

// import EditNews from './components/editNews'
import NewsShow from './components/show'
import { addConfig } from 'actions/config'
import Ajax from 'lib/Ajax'
import { getNameByCode, confirmDelete, findRowData } from 'lib/fun'
const FormItem = Form.Item;
const Option = Select.Option;

class ModuleName extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      visible: false,
      editType: "",
      rowdata: {},
      data: [],
      visible2: false,
      feedbackId: ""
    }
    // 翻页相关
    this.current = 1;   //当前第几页
    this.total = 10;   //总共多少页
    this.pageSize = 10;   //每页多少行
    this.search = {};
  }

  componentDidMount(){
    this.loadData();
  }

  handleFilter = (option)=>{
    var self = this;
    if(!_.isEqual(option, this.search)){
      this.search = option;
      self.loadData();
    }
  }
  pageOnChange = (page)=>{
    this.current = page;
    this.loadData();
  }

  showSizeChange = (current, pageSize)=>{
    var page = Math.ceil(((this.current-1)*this.pageSize+1)/pageSize);
    this.pageSize = pageSize;
    this.current = page;
    this.loadData();
  }

  loadData = ()=>{
    var self = this;
    self.setState({
      loading: true
    });
    Ajax({
      url: '/feedback/list',
      data: {
        "title": self.search.title,
        "state": self.search.state == undefined?undefined:self.search.state,    //状态
        "currentPage": self.current,  //请求页码
        "perPage": self.pageSize,   //每页数量
      },
      success: function(data){
        self.total = data.totalCount;
        self.setState({
          loading: false,
          data: data.list
        });
      },
      error: function(error){
        self.setState({
          loading: false
        });
        message.error(error);
      }
    });
  }

  // 操作
  operate = (type, row)=>{
    if(type == 'edit'){
      this.setState({
        visible: true,
        editType: 'edit',
        rowdata: row
      });
    }else{
      this.setState({
        visible: true,
        editType: 'new'
      });
    }
  }

  editOk = (type, rowdata)=>{
    var self = this;
    if(type == 'edit'){
      var find = _.find(self.state.data, (item)=>{
        return item.feedbackId == rowdata.feedbackId
      });
      Object.assign(find, rowdata);
      message.success('修改记录成功！');
    }else{
      self.state.data.unshift(rowdata);
      message.success('增加记录成功！');
    }
    self.setState({
      visible: false,
      rowdata: {},
      data: self.state.data
    });
  }
  editCancel = ()=>{
    this.setState({
      visible: false,
      rowdata: {}
    });
  }
  onClose = ()=>{
    this.setState({
      settingVisible: false,
      rowdata: {}
    });
  }

  doDelete = (id)=>{
    var self = this;
    confirmDelete(()=>{
      Ajax({
        url: '/news/delete',
        data: {
          "feedbackId": id
        },
        success: function(data){
          // _.remove(self.state.data, function(d) {
          //   return d.feedbackId == id
          // });
          // self.setState({
          //   data: self.state.data
          // });
          self.loadData();
        },
        error: function(error){
          message.error(error);
        }
      });
    }, ()=>{
      message.info('取消删除');
    });
  }

  render() {
    var pagination = {
      current: this.current,
      total: this.total,
      pageSize: this.pageSize,
      onChange: this.pageOnChange,
      showSizeChanger: true,
      onShowSizeChange: this.showSizeChange
    };

    const { config } = this.props;
    const newsTypes = this.props.common.newsTypeEn||[];
    const getNewsTypeName = (text)=>{
      var find = _.find(newsTypes, (item)=>{
        return item.code == text
      })
      if(find){
        return find.mean
      }else{
        return ""
      }
    }
    
    const columns = [{
        title: 'ID',
        dataIndex: 'id'
      }, {
        title: '新闻标题',
        dataIndex: 'title',
        render: (text, record) => (<a href="javascript:;" onClick={()=>{
          this.setState({
            feedbackId: record.id,
            visible2: true
          })
        }}>{text}</a>)
      }, {
        title: '姓名',
        dataIndex: 'name'
      }, {
        title: '联系方式',
        dataIndex: 'tel'
      }, {
        title: '单位',
        dataIndex: 'company'
      }, {
        title: '状态',
        dataIndex: 'state'
      }, {
        title: '创建时间',
        dataIndex: 'createTime'
      }];

// title={() => (<div>
//                             <Button type="primary" style={{marginRight: 15}} icon="plus" onClick={ this.operate.bind(this, 'new') }>新建</Button>
//                           </div>)}
    return (
      <div className="area">
        <FilterModule 
          handleFilter={ this.handleFilter }
        />
        <div className="area-con">
          <Table
            columns={ columns }
            dataSource={ this.state.data }
            pagination={ pagination }
            loading={this.state.loading}
            rowKey="feedbackId"
          />
        </div>
      {/*
        <EditNews
          visible={ this.state.visible }
          onOk={ this.editOk }
          onCancel={ this.editCancel }
          type={ this.state.editType }
          rowdata={ this.state.rowdata }
          config={ this.props.config }
        />
      */}
        <NewsShow
          onClose={()=>{
            this.setState({
              visible2: false
            })
          }}
          feedbackId={this.state.feedbackId}
          visible={this.state.visible2}
        />
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    common: state.common
  }
}

function mapDispatchToProps(dispatch) {
  return bindActionCreators({ addConfig }, dispatch)
}

module.exports = connect(mapStateToProps,mapDispatchToProps)(ModuleName)

class Filter extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount(){
  }

  handleSearch = (e) => {
    var self = this;
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      self.props.handleFilter(values);
    });
  }

  handleReset = () => {
    this.props.form.resetFields();
  }

  render() {
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: { span: 10 },
      wrapperCol: { span: 14 },
    };
    const feedbackStateEn = this.props.common.feedbackStateEn||[]
    return (<Form
          horizontal
          className="ant-advanced-search-form"
          onSubmit={this.handleSearch}
        >
          <Row gutter={10}>
            <Col span={8}>
              <FormItem {...formItemLayout} label="标题">
                {getFieldDecorator("title")(
                  <Input />
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <FormItem {...formItemLayout} label="状态">
                {getFieldDecorator("state")(
                  <Select
                    size="default"
                    allowClear
                  >
                    {
                      feedbackStateEn.map(function(obj){
                        return (<Option key={obj.code+""} value={ obj.code+"" }>{ obj.mean }</Option>)
                      })
                    }
                  </Select>
                )}
              </FormItem>
            </Col>
            <Col span={8}>
              <div className="btn-box">
                <Button type="primary" htmlType="submit">查询</Button>
                <Button style={{ marginLeft: 8 }} onClick={this.handleReset}>
                  重置
                </Button>
              </div>
            </Col>
          </Row>
        </Form>);
  }
}

var FilterModule = Form.create()(connect(function(state) {
  return {
    common: state.common
  }
})(Filter))
